package com.example.administrator.netdemo.network;

import android.content.Context;

import com.example.administrator.netdemo.BuildConfig;
import com.example.administrator.netdemo.network.base.ApiService;
import com.example.administrator.netdemo.network.gsonConverter.MyGsonConverterFactory;

import java.io.File;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;

import okhttp3.Cache;
import okhttp3.Cookie;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;

/**
 * Created by luquan on 2017/2/10.
 */

public class RequestHandler {

    private Retrofit retrofit;
    public final static int CONNECT_TIMEOUT_SECOND = 30;
    public final static int READ_TIMEOUT_SECOND = 30;
    public final static int WRITE_TIMEOUT_SECOND = 30;

    private RequestHandler() {
    }

    private static class SingletonHolder {
        private static final RequestHandler INSTANCE = new RequestHandler();
    }

    public static RequestHandler getInstance() {
        return SingletonHolder.INSTANCE;
    }

    private ApiService mApiService;
    ConcurrentHashMap<String, List<Cookie>> cookieStore = new ConcurrentHashMap<>();

    public ApiService getApiService(Context context) {
        if (mApiService == null) {
            HttpLoggingInterceptor logInterceptor = new HttpLoggingInterceptor();//print log
            logInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

            File cacheFile = new File(context.getCacheDir(), "respCache");
            Cache cache = new Cache(cacheFile, 1024 * 1024 * 1000); //1000Mb
            OkHttpClient.Builder builder = new OkHttpClient.Builder()
                    .addInterceptor(new ParameterInterceptor())//所有图片文件使用请求需要的参数
                    .retryOnConnectionFailure(true)
                    .connectTimeout(CONNECT_TIMEOUT_SECOND, TimeUnit.SECONDS)
                    .readTimeout(READ_TIMEOUT_SECOND, TimeUnit.SECONDS)
                    .writeTimeout(WRITE_TIMEOUT_SECOND, TimeUnit.SECONDS)
//                    .addNetworkInterceptor(new CacheInterceptor())
                    .cache(cache);

            if (BuildConfig.DEBUG) {
                builder.addInterceptor(logInterceptor);
            }

            String baseUrl = BuildConfig.SERVER_HOST;
            OkHttpClient client = builder.build();

            retrofit = new Retrofit.Builder()
                    .client(client)
                    .baseUrl(baseUrl)
                    .addConverterFactory(MyGsonConverterFactory.create())
                    .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                    .build();
            mApiService = retrofit.create(ApiService.class);

        }
        return mApiService;
    }



}
